import COS from 'cos-js-sdk-v5';
import request from "../../request"
import dayjs from 'dayjs';
import { v4 as uuidv4 } from 'uuid';
import store from "@/store"

export function createUploadFileName(uploadFile) {
    let fileExtension = uploadFile.name.split('.').pop(),
        uniqueId = uuidv4().replace(/-/g, '');

    return 'upload/work_ai/' + dayjs().locale('zh-cn').format('YYYY-MM-DD') + '/' + uniqueId + '.' + fileExtension;
}

export function createCosInstance() {
    return new COS({
        getAuthorization: function (options, callback) {
            request.post('/work_ai', '/upload/cos/config', {
                scopes: options.Scope
            }).then(res => {
                const credentials = res.credentials;

                if(! credentials){
                    throw new Error('获取临时凭证失败')
                }

                console.log(credentials, 'Cos 临时凭证信息')

                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    SecurityToken: credentials.sessionToken,
                    StartTime: res.startTime,
                    ExpiredTime: res.expiredTime,
                    ScopeLimit: true,
                });
            })
        }
    });
}

function uploadFile(uploadFile, config = {}) {
    return new Promise(async (resolve, reject) => {
        const cos = createCosInstance();
        const aiConfig = await store.dispatch("getAiConfig")
        const fileName = createUploadFileName(uploadFile)

        cos.uploadFile({
            Bucket: aiConfig.cos_config.bucket,
            Region: aiConfig.cos_config.region,
            Key: fileName,
            Body: uploadFile,
            SliceSize: 1024 * 1024 * 5,
            AsyncLimit: 3,
            onProgress: (progressData) => {
                console.log(progressData, 'cos progressData')
                config.onUploadProgress && config.onUploadProgress(progressData)
            },
        }, (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve({
                    name: uploadFile.name,
                    size: uploadFile.size,
                    fileName,
                    fileUrl: aiConfig.cos_config.domain + '/' + fileName
                })
            }
        })
    })
}

export async function uploadFiles(uploadFiles, config = {}) {
    return new Promise(async (resolve, reject) => {
        const cos = createCosInstance();
        const aiConfig = await store.dispatch("getAiConfig")

        for(let uploadFile of uploadFiles){
            uploadFile.fileName = createUploadFileName(uploadFile)
        }

        cos.uploadFiles({
            files: uploadFiles.map(uploadFile => ({
                Bucket: aiConfig.cos_config.bucket,
                Region: aiConfig.cos_config.region,
                Key: uploadFile.fileName,
                Body: uploadFile,
            })),
            SliceSize: 1024 * 1024 * 5,
            AsyncLimit: 3,
            onProgress: (progressData) => {
                console.log(progressData)
                config.onUploadProgress && config.onUploadProgress(progressData)
            },
            onFileFinish: function (err, data, options) {
                console.log(options.Key + '上传' + (err ? '失败' : '完成'));
            },
        }, (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve(
                    uploadFiles.map(uploadFile => ({
                        name: uploadFile.name,
                        size: uploadFile.size,
                        fileName: uploadFile.fileName,
                        fileUrl: aiConfig.cos_config.domain + '/' + uploadFile.fileName,
                    }))
                )
            }
        })
    })
}

export async function upload(file, config = {}) {
    if(Array.isArray(file)){
        return uploadFiles(file, config)
    }

    return uploadFile(file, config)
}